const express = require('express');
const router = express.Router();
const deptController = require('../../controllers/deptController');
const { validateRequest } = require('../../middleware/validationMiddleware');
const { body, param, query } = require('express-validator');

// 创建部门
router.post('/dept',
    [
        body('name').notEmpty().withMessage('部门名称不能为空'),
        body('parent_id').notEmpty().isInt().withMessage('父级部门ID必须为整数'),
        body('tree_path').notEmpty().withMessage('tree_path不能为空'),
        body('sort').optional().isInt().withMessage('排序值必须为整数'),
        body('status').optional().isIn([0, 1]).withMessage('状态值只能为0或1')
    ],
    validateRequest,
    deptController.createDept
);

// 更新部门
router.put('/dept/:id',
    [
        param('id').isInt().withMessage('无效的部门ID'),
        body('name').optional().notEmpty().withMessage('部门名称不能为空'),
        body('parent_id').optional().isInt().withMessage('父级部门ID必须为整数'),
        body('sort').optional().isInt().withMessage('排序值必须为整数'),
        body('status').optional().isIn([0, 1]).withMessage('状态值只能为0或1')
    ],
    validateRequest,
    deptController.updateDept
);

// 删除部门
router.delete('/dept/:id',
    [
        param('id').isInt().withMessage('无效的部门ID')
    ],
    validateRequest,
    deptController.deleteDept
);

// 获取部门列表
router.get('/dept/page',
    [
        query('pageNum').exists().withMessage('pageNum参数缺失')
            .isInt({ min: 1 }).withMessage('pageNum必须为大于0的整数'),
            query('pageSize').exists().withMessage('pageSize参数缺失')
            .isInt({ min: 1, max: 100 }).withMessage('pageSize必须为1-100之间的整数'),
            query('name').optional().isString(),
            query('status').optional().isIn(['0', '1']).withMessage('状态值只能为0或1')
    ],
    validateRequest,
    deptController.getDeptList
);

// 获取部门树形结构
router.get('/dept/tree',
    [
        query('keywords').optional().isString().withMessage('部门名称必须为字符串'),
        query('status').optional().isIn(['0', '1']).withMessage('状态值只能为0或1')
    ],
    validateRequest,
    deptController.getDeptTree
);


// 获取部门下拉选项
router.get('/dept/options',
    deptController.getDeptOptions
);


// 获取部门详情
router.get('/dept/:id',
    [
        param('id').isInt().withMessage('无效的部门ID')
    ],
    validateRequest,
    deptController.getDeptById
);

module.exports = router;